<?php
/**
 * Created by PhpStorm.
 * User: xuanqiang
 * Date: 2018/2/6
 * Time: 10:56
 */

namespace app\wechat\controller;

use app\wechat\WxController;
use think\Controller;

class Template extends Controller
{
    protected $baseTemplateUrl = 'https://api.weixin.qq.com/cgi-bin';
    protected $url = 'https://www.emiaoqian.com'; //点击模板后跳转地址
    protected $accessToken;

    public function __construct(){
        parent::__construct();
//        $wx = new WxController();
//        $this->accessToken = $wx->getWxAccessToken();
        $this->accessToken = wx_get_token();
    }
    public function index(){
        echo 11;
    }

    //根据模板库中的编号获取模板id
//    public function getTemplateId(){
//
//        $requestUrl = $this->baseTemplateUrl.'/template/api_add_template?access_token='.$this->accessToken;
//        $data = ["template_id_short" => "TM00200"]; //模板库中的编号
//        $resultData = WxController::send($requestUrl,$data,'POST');
//        var_dump($resultData);
//    }

    //获取所有的模板列表-获取模板id
    public function getAllPrivateTemplate(){
        $requestUrl = $this->baseTemplateUrl.'/template/get_all_private_template?access_token='.$this->accessToken;
        $resultData = BaseToken::send($requestUrl);
        var_dump($resultData) ;
    }

    //发送模板消息
    public function sendTemplateMessage($openId,$templateId,$data,$url='',$miniprogram =[]){
        $requestUrl = $this->baseTemplateUrl.'/message/template/send?access_token='.$this->accessToken;
        $posArr = [
            'touser' => $openId,          //用户openid
            'template_id' => $templateId, //发送模板消息Id
            'data' => $data,               //发送内容
        ];
        $posData = json_encode($posArr);
        if($url != ''){
           $posArr['url'] = $url;
        }
        if(count($miniprogram) != 0){
            $posArr['miniprogram'] = $miniprogram;
        }
        $resultData = BaseToken::send($requestUrl,$posData,'POST');
        return $resultData;
    }

    //发送快递类消息，根据所选模板的不同，data的格式不同
    public function sendExpressMessage(){
        $openId ='oBvyv1ahFzldTaxjhiBLEUENGuAQ';
        $templateId = 'F79jdrgcIDaDi3XwDqUcI7KnBN2ra1Kw1Ul1wCqy54U'; //快递类模板id

        $data = [ //快递类模板数据格式
            'channel' => ['value' => '秒签速递',"color"=>"#173177"],
            'orderNumber' => ['value' => 'T10001',"color"=>"#173177"],
            'state' => ['value' => '已签收',"color"=>"#173177"],
            'doSomething' => ['value' => '放在门口',"color"=>"#173177"],
            'remark' => ['value' => '请查收',"color"=>"#173177"]
        ];
        $url = "https://www.emiaoqian.com";
        $miniprogram = [
            'appid' => '',
            'pagepath' => 'index'
        ];
        $result =  $this->sendTemplateMessage($openId,$templateId,$data,$url,$miniprogram);
        var_dump($result);
    }
}